<?php

namespace App\Handlers;

use Illuminate\Support\Facades\Redis;

//WS操作类
class WSHandler
{
    //用于保存用户标志和fd对应关系的RedisKey键
    private const REDIS_KEY_USERID_FD = ':WSUserIds:fds';

    private static $redisConnection = null;

    //客户端连接WS服务器,触发onOpen事件,将用户唯一标识符和对应的socketFd对应关系保存
    static function setFd(string $userId, int $fd) : bool
    {
        if (! self::$redisConnection) {
            self::$redisConnection = Redis::connection('WS');
        }
        if (self::$redisConnection->hExists(self::REDIS_KEY_USERID_FD, $userId)) {
            self::delByUserId($userId);
        }
        return self::$redisConnection->hSet(self::REDIS_KEY_USERID_FD, $userId, $fd);
    }

    static function getFd(string $userId) : int
    {
        if (! self::$redisConnection) {
            self::$redisConnection = Redis::connection('WS');
        }
        return (int)self::$redisConnection->hGet(self::REDIS_KEY_USERID_FD, $userId);
    }

    //根据userId删掉项
    static function delByUserId(string $userId) : void
    {
        if (! self::$redisConnection) {
            self::$redisConnection = Redis::connection('WS');
        }
        self::$redisConnection->hDel(self::REDIS_KEY_USERID_FD, $userId);
    }

    //根据fd删掉项
    static function delByFd(int $fd) :void
    {
        if (! self::$redisConnection) {
            self::$redisConnection = Redis::connection('WS');
        }
        foreach (self::$redisConnection->hGetAll(self::REDIS_KEY_USERID_FD) as $field => $value) {
            if ($value == $fd) {
                self::$redisConnection->hDel(self::REDIS_KEY_USERID_FD, $field);
                break;
            }
        }
    }
}
